<template>
    <Row>
        <Card>
            <Row>
                <Form class="form-row" ref="search" :model="params" label-position="right" :label-width="90" inline>
                    <FormItem label="停车场" prop="parkingName">
                        <div class="filters-input">
                            <el-select v-model="params.parkingId" placeholder="请选择停车场" class="normal-input"
                                       :clearable="true">
                                <el-option v-for="item in parkingData" :value="item.id" :key="item.id" :label="item.parkingName">
                                </el-option>
                            </el-select>
                        </div>
                    </FormItem>
                    <FormItem label="车牌号" prop="parking-name">
                        <div class="filters-input">
                            <Input type="text" v-model="params.carNum" placeholder="请输入车牌号"
                                   class="normal-input"></Input>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSearch">搜索</Button>
                    </FormItem>
                </Form>
            </Row>
            <Row class="form-row">
                <Button type="primary" icon="md-add" @click="modalEdit = true;modalType = 'add';carInfo = {}"
                        style="margin-right: 10px;">新增
                </Button>
                <Tooltip content="这是批量导入的模板">
                    <Button type="info" icon="md-download" @click="download()" style="margin-right: 10px;">下载模板</Button>
                </Tooltip>
                <Button type="warning" icon="ios-undo" @click="importCarInfo()" style="margin-right: 10px;">导入模板
                </Button>
            </Row>
            <Table stripe :columns="titleTable" :data="data.list ? data.list : []"></Table>
            <Page style="margin: 10px 0;" :total="data.total" :current="data.pageNum" :page-size="data.pageSize"
                  show-total show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </Card>
        <Modal v-model="modalEdit" :title="modalType == 'add' ? '新增': '修改'">
            <Form ref="saveCarInfo" :model="carInfo" :rules="saveCarInfoValidateRules" :label-width="90">
                <FormItem label="停车场" prop="parkingId">
                    <Select v-model="carInfo.parkingId" class="normal-input" @on-change="handleParkingSelectChanged"
                            :clearable="true">
                        <Option v-for="item in parkingData" :value="item.id" :key="item.id">{{ item.parkingName }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="车牌号" prop="carNum">
                    <Input v-model="carInfo.carNum" placeholder="车牌号" class="normal-input"></Input>
                </FormItem>
                <FormItem label="车辆类型" prop="carType">
                    <Select v-model="carInfo.carType" placeholder="请选择车辆类型" class="normal-input" :clearable="true">
                        <Option value="小型车">小型车</Option>
                        <Option value="中型车">中型车</Option>
                        <Option value="中型车">中型车</Option>
                    </Select>
                </FormItem>
                <FormItem label="收费模式" prop="carModelName">
                    <Select v-model="carInfo.carModelName" placeholder="请选择收费模式" class="normal-input" :clearable="true">
                        <Option value="免费车">免费车(固定车位)</Option>
                        <Option value="月租车">月租车</Option>
                        <Option value="预约车">预约车</Option>
                    </Select>
                </FormItem>
                <FormItem label="车位编号" prop="spaceNo">
                    <Input v-model="carInfo.spaceNo" placeholder="车位编号" class="normal-input"></Input>
                </FormItem>
                <FormItem label="月租开始时间" prop="monthStartTime">
                    <DatePicker v-model="tempData.monthStartTime" format="yyyy-MM-dd" type="date" placeholder="请选择开始时间"
                                @on-change="handleStartTimeChange" class="normal-input"></DatePicker>
                </FormItem>
                <FormItem label="月租结束时间" prop="monthEndTime">
                    <DatePicker v-model="tempData.monthEndTime" format="yyyy-MM-dd" type="date" placeholder="请选择结束时间"
                                @on-change="handleEndTimeChange" class="normal-input"></DatePicker>
                </FormItem>
                <FormItem label="业主房屋" prop="houseId">
                    <Select v-model="carInfo.houseId" class="normal-input" :clearable="true">
                        <Option v-for="item in roomList" :value="item.id" :key="item.id">{{ item.groupName + ' ' +
                            item.building + '' + item.unit + ' ' + item.room}}
                        </Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="onCancel()">关闭</Button>
                <Button type="primary" size="large" @click="handleSubmit" :loading="saveCarInfoLoading">确定</Button>
            </div>
        </Modal>

        <Modal v-model="modalCarInfo" title="导入车辆信息" class="modal-content" :mask-closable="false">
            <Form :model="carModal" :rules="rule" ref="fileform" label-position="right" :label-width="100"
                  class="myOpenFrom">
                <FormItem label="停车场" prop="parkingId">
                    <el-select v-model="carModal.parkingId" filterable placeholder="请选择停车库"
                               clearable no-data-text="暂无数据" style="width: 100%">
                        <el-option v-for="item in parkingData" :value="item.id" :key="item.id"
                                   :label="item.parkingName"></el-option>
                    </el-select>
                </FormItem>
                <FormItem label="上传文件">
                    <el-upload class="upload-demo" :data="dataFile" ref="upload" :action="act"
                               :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList"
                               :auto-upload="false" accept=".xlsx,.xls,.csv" :headers="{'x-access-token':token}"
                               :on-success="filesuccess" :on-error="filefail" :limit="1" :multiple="false">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传.xlsx/.xls/.csv文件</div>
                    </el-upload>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="onCancel">取消</Button>
                <Button type="primary" @click="submitUpload" :loading="formLoading">确定</Button>
            </div>
        </Modal>

    </Row>
</template>

<script>
    //线上下载模板地址
    import baseURL from "_conf/url";
    import Cookies from "js-cookie";
    import {TOKEN_KEY} from "@/libs/util";
    //线上上传地址
    const act = baseURL + "/api/parking/car/info/batch";
    const token = Cookies.get(TOKEN_KEY);
    //校验规则
    const rules = {
        parkingId: [
            {
                required: true,
                message: "请选择停车场"
            }
        ],
    };
    export default {
        name: "list",
        data() {
            return {
                //验证规则
                rule: rules,
                params: {},
                modalEdit: false,
                //导入车辆信息
                modalCarInfo: false,
                //上传文件
                dataFile: {},
                //文件上传地址
                act: act,
                //停车场列表
                parkingList: [],
                //表单提交状态
                formLoading: false,
                carModal: {},
                modalType: 'add',
                titleTable: [
                    {
                        title: '停车场名称',
                        key: 'parkingName'
                    },
                    {
                        title: '车牌号',
                        key: 'carNum'
                    },
                    {
                        title: '收费模式',
                        key: 'carModelName'
                    },
                    {
                        title: '月租开始时间',
                        key: 'monthStartTime'
                    },
                    {
                        title: '月租结束时间',
                        key: 'monthEndTime'
                    },
                    {
                        title: '操作',
                        align: "center",
                        width: 150,
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    on: {
                                        'click': () => {
                                            this.handleModify(params.row)
                                        }
                                    },
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    }
                                }, '修改'),
                                h('Button', {
                                    on: {
                                        'click': () => {
                                            this.handleDelete(params.row)
                                        }
                                    },
                                    props: {
                                        type: 'warning',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    }
                                }, '删除'),
                            ])
                        }

                    }
                ],
                data: {
                    pageNum: 1,
                    pageSize: 10,
                },
                parkingData: [],
                carInfo: {},
                saveCarInfoLoading: false,
                saveCarInfoValidateRules: {
                    carNum: [
                        {required: true, message: "请输入车牌号", trigger: "blur"}
                    ],

                },
                roomList: [],
                tempData: {},
                //文件上传地址
                token: token,
                fileList: []
            }
        },
        created: function () {
            this.init()
        },
        methods: {
            init: function () {
                this.getRequest('/api/parking/all').then(res => {
                    console.log(res)
                    if (res.code == 20000) {
                        this.parkingData = res.data
                    }
                })
                this.loadData()
            },
            loadData: function () {
                let url = "/api/parking/cars?page_num=" + this.data.pageNum + "&page_size=" + this.data.pageSize
                if (this.params.parkingId) {
                    url += "&parking_id=" + this.params.parkingId
                }
                if (this.params.carNum && this.params.carNum != '') {
                    url = url + '&search_text=' + this.params.carNum
                }
                this.getRequest(url).then(resp => {
                    console.log(resp)
                    if (resp.code == 20000) {
                        if (resp.data != null) {
                            this.data = resp.data
                        }
                        return;
                    }
                    this.$Message.error(resp.message)
                })
            },
            saveCarInfo: function () {
                const url = "/api/parking/car/save"
                this.postRequest(url, this.carInfo).then(resp => {
                    console.log(resp)
                    this.saveCarInfoLoading = false
                    if (resp.code == 20000) {
                        this.modalEdit = false
                        this.loadData()
                        return
                    }
                    this.$Message.error(resp.message)

                })
            },
            getRoomList: function (parkingId) {
                const url = "/api/parking/room/list/" + parkingId
                this.getRequest(url).then(resp => {
                    console.log(resp)
                    if (resp.code == 20000) {
                        this.roomList = resp.data
                        return
                    }
                    this.$Message.error(resp.message)
                })
            },
            handleSearch: function () {
                this.loadData()
            },
            handleModify: function (row) {
                console.log(row)
                this.modalEdit = true
                this.modalType = 'edit'
                // row.houseId = new String(row.houseId).toString()
                this.tempData.monthStartTime = new Date(row.monthStartTime)
                this.tempData.monthEndTime = new Date(row.monthEndTime)
                this.carInfo = row
                this.getRoomList(row.parkingId)

            },
            handleDelete: function (row) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '确定删除此出入口信息？',
                    onOk: () => {
                        row.isEnable = false
                        this.carInfo = row
                        this.saveCarInfo()
                        // this.$Message.info('Clicked ok');
                    },
                    onCancel: () => {

                    }
                })
            },
            handleStartTimeChange: function (date) {
                console.log(date)
                this.carInfo.monthStartTime = date + " 00:00:00"
            },
            handleEndTimeChange: function (date) {
                this.carInfo.monthEndTime = date + " 23:59:59"
            },
            handlePage(value) {
                this.data.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.data.pageSize = value;
                this.loadData();
            },
            onCancel: function () {
                this.modalEdit = false;
                this.modalCarInfo = false;
            },
            handleSubmit: function () {
                this.$refs['saveCarInfo'].validate(valid => {
                    if (valid) {
                        this.saveCarInfo()
                    }
                })
            },
            handleParkingSelectChanged: function (e) {
                console.log(e)
                if (e && e != undefined)
                    this.getRoomList(e)
            },
            // 下载模板
            download: function () {
                let url = "http://oss.siyueluo.com/template/%E8%BD%A6%E8%BE%86%E4%BF%A1%E6%81%AF%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx";
                window.location.href = url;
            },
            //导入车辆信息
            importCarInfo: function () {
                this.modalCarInfo = true;
            },
            // 文件上传相关

            handleRemove(file, fileList) {
                // console.log(file, fileList);
            },
            handlePreview(file) {
                // console.log(file);
                this.file = file;
            },
            //文件上传
            submitUpload() {
                this.$refs["fileform"].validate(valid => {
                    if (valid) {
                        if (this.file == null) {
                            this.$Message.error("请上传文件");
                        } else {
                            this.dataFile.parkingId = this.carModal.parkingId;
                            console.log(this.dataFile.parkingId);
                            this.$refs.upload.submit();
                            this.$refs.fileselect.clearSingleSelect();
                            this.modalCarInfo = false;
                        }
                    }
                });
            },
            filesuccess(response, file) {
                if (response.code == 20000) {
                    this.$Message.success({
                        content: response.message,
                        duration: 5
                    });
                    this.loadData();
                } else {
                    this.$Modal.error({
                        title: "上传失败",
                        content: response.message
                    });
                }
                this.onCancel();
                this.$refs.upload.clearFiles();
                // console.log(response)
            },
            filefail(response) {
                // console.log(response);
                this.onCancel();
                this.$Modal.error({
                    title: "上传失败",
                    content: "请稍后再试"
                });
                this.$refs.upload.clearFiles();
            },
        }
    }
</script>

<style scoped>
    .normal-input {
        width: 250px;
    }
</style>
